package com.boot.proofing.common.config;/**
 * @description
 * @autor xbwu on 2018/12/26.
 */

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
 * 全局事务配置
 * @author xbwu
 * @create 2018-12-26 
 **/
@Aspect
@Configuration
public class TransactionAdviceConfig {
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.***.service.impl..*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice() {

        DefaultTransactionAttribute txAttrREQUIRED = new DefaultTransactionAttribute();
        txAttrREQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        DefaultTransactionAttribute txAttrREQUIRED_READONLY = new DefaultTransactionAttribute();
        txAttrREQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        txAttrREQUIRED_READONLY.setReadOnly(true);

        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.addTransactionalMethod("add*", txAttrREQUIRED);
        source.addTransactionalMethod("save*", txAttrREQUIRED);
        source.addTransactionalMethod("delete*", txAttrREQUIRED);
        source.addTransactionalMethod("remove*", txAttrREQUIRED);
        source.addTransactionalMethod("update*", txAttrREQUIRED);
        source.addTransactionalMethod("select*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("get*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("query*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("find*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("list*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("count*", txAttrREQUIRED_READONLY);
        source.addTransactionalMethod("page*", txAttrREQUIRED_READONLY);
        return new TransactionInterceptor(transactionManager, source);
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}
